package com.wocai.jrt.orgadmin.feedback.action;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wocai.jrt.orgadmin.feedback.model.Feedback;
import com.wocai.jrt.orgadmin.feedback.service.spi.FeedbackService;
import com.wocai.jrt.orgadmin.utils.UserUtils;
import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;

/**
 * 意见反馈控制器
 * @author zhangyz
 * @date 2015-8-20 15:53:24
 */
@Controller
@RequestMapping("/feedback")
public class FeedbackAction extends GenericAction<Feedback> {
	private static final Logger LOGGER = LoggerFactory.getLogger(FeedbackAction.class);
	
	@Inject
	private FeedbackService feedbackServiceImpl;
	
	/**
     * 获得意见反馈List，初始化列表页。
     * @param model 参数
     * @return 意见反馈List
     */
    @RequestMapping("/list")
    public String list(Feedback model, Map<String, Object> maps) {
        return "feedback/list";
    }
	
    /**
	 *  
	 * @param model 参数
	 * @return 意见反馈List
	 */
	@ResponseBody
	@RequestMapping("/query")
	public Map<String, Object> query(@RequestBody Feedback model) {
		Map<String, Object> result = new HashMap<String, Object>();
    	try {
    		Date date = model.getEndTime();
    		if (date!=null) {
    			model.setEndTime(new DateTime(date).plusHours(23).plusMinutes(59).plusSeconds(59).toDate());
			}
    		//获取当前机构ID
		    model.setOrgId(UserUtils.getOrgId());
		    model.setOrderBy("create_time desc");
    		List<Feedback> list = feedbackServiceImpl.queryMyList(model);
    		// 统计的时候，不需要分页
    		model.setPage(null);
    		long totalRecord  = feedbackServiceImpl.queryMyList(model).size();
    		
    		if (LOGGER.isDebugEnabled()) {
    			LOGGER.debug("feedback query success.");
    		}
    		result.put("aaData", list); // 返回的数据
    		result.put("iTotalRecords", totalRecord); // 总记录数
    		result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("feedback query error, msg=[{}]", e.getMessage());
		}
        return result;
	}
	
	/**
     * 将反馈提交到平台
     * @param model
     * @return JsonBean
     */
    @ResponseBody
    @RequestMapping("/submit")
    public JsonBean submit(@RequestBody Feedback model) {
    	JsonBean bean = new JsonBean();
    	if(StringUtils.isBlank(model.getId())){
    		bean.setCode(0);
    		bean.setMessage("参数错误");
    		return bean;
    	}
    	try {
    		int result = feedbackServiceImpl.submit(model);
    		if (result == 1) {
    			bean.setCode(1);
        		bean.setData(result);
        		bean.setMessage("已成功提交到平台!");
			}else{
				bean.setCode(0);
        		bean.setData(result);
        		bean.setMessage("提交到平台失败!");
			}
		} catch (Exception e) {
			LOGGER.error("get record error, errorMsg=[{}].", e.getMessage());
			bean.setCode(0);
    		bean.setMessage("提交到平台失败!"+e.getMessage());
		}
        return bean;
    }
	   
    /**
     * 添加反馈回复
     * @param model 
     * @return JsonBean
     */
    @ResponseBody
    @RequestMapping("/addReply")
    public JsonBean addReply(@RequestBody Feedback model) {
    	JsonBean bean = new JsonBean();
    	if(StringUtils.isBlank(model.getFeedbackId())||StringUtils.isBlank(model.getReplyContent())){
    		 bean.setMessage("参数错误");
             bean.setCode(0);
             return bean;	
    	}
    	model.setOrgId(UserUtils.getOrgId());
    	model.setId(ObjectId.get().toString());
    	model.setReplyTime(new Date());
    	model.setEmployeeId(UserUtils.getUserId());
    	try {
    		int result = feedbackServiceImpl.addReply(model);
            if (result == 1) {
            	//更新反馈状态为已回复
            	feedbackServiceImpl.updateReplyState(model.getFeedbackId());
                bean.setMessage("反馈已成功回复");
                bean.setCode(1);
                LOGGER.info("addReply record success.");
            } else {
                bean.setMessage("反馈已失败回复");
                bean.setCode(0);
                LOGGER.error("addReply record error.");
            }
		} catch (Exception e) {
			 LOGGER.error("addReply record error, errorMsg=[{}].", e.getMessage());
			 bean.setCode(0);
			 bean.setMessage(ERROR);
		}
        return bean;
    }
    
    /**
     * 查看意见反馈详情页。
     * @param model 查询参数，携带ID
     * @return 意见反馈详情页
     */
    @RequestMapping("/detail/{id}")
    public String detail(@PathVariable("id") String id, Map<String, Object> maps) {
    	Feedback model = new Feedback();
    	try {
    		model = feedbackServiceImpl.getDetail(id);
            maps.put("model", model);//将model放入视图中，供页面视图使用
            LOGGER.error("query feedback detail success");
		} catch (Exception e) {
			LOGGER.error("query feedback detail errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
        return "feedback/detail";
    }
  
}
